<template>
  <div class="device-management">
    <h2>设备管理</h2>
    <p>管理智能健身衣设备，可进行设备添加、状态监控、解绑等操作。</p>

    <div class="add-bar">
      <input v-model="newDeviceId" placeholder="输入新设备ID" />
      <button @click="addDevice">添加设备</button>
    </div>

    <table>
      <thead>
        <tr><th>设备ID</th><th>状态</th><th>操作</th></tr>
      </thead>
      <tbody>
        <tr v-for="d in devices" :key="d.id">
          <td>{{ d.id }}</td>
          <td>
            <span :style="{ color: d.status ? 'green' : 'red' }">
              {{ d.status ? '使用中' : '空闲中' }}
            </span>
          </td>
          <td>
            <button @click="unbindDevice(d.id)" style="color:#ff5252;">解绑</button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 分页控件 -->
    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>第 {{ currentPage }} / {{ totalPages }} 页</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'

// 存储设备列表数据
const devices = ref([])

// 新增设备输入框的值
const newDeviceId = ref('')

// 分页相关变量
const currentPage = ref(1)
const pageSize = ref(10) // 每页显示数量
const totalItems = ref(0)

/**
 * 获取设备总数（用于计算总页数）
 */
async function fetchTotalCount() {
  const res = await fetch('http://47.108.221.119:5000/getdevicecount')
  if (res.ok) {
    const data = await res.json()
    totalItems.value = data.count
  } else {
    console.error('获取设备总数失败')
  }
}

/**
 * 获取设备列表（GET）
 */
 async function fetchDevices(page = 1, size = 10) {
  const res = await fetch(`http://47.108.221.119:5000/getdevicelist?page=${page}&size=${size}`)
  if (res.ok) {
    const data = await res.json()
    devices.value = data.map(device => ({
      ...device,
      status: Boolean(device.status) // 确保是布尔值
    }))
  } else {
    console.error('获取设备失败')
  }
}
/**
 * 上一页
 */
function prevPage() {
  if (currentPage.value > 1) {
    currentPage.value--
    fetchData()
  }
}

/**
 * 下一页
 */
function nextPage() {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    fetchData()
  }
}

/**
 * 加载数据
 */
function fetchData() {
  fetchDevices(currentPage.value, pageSize.value)
}

/**
 * 计算总页数
 */
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))

onMounted(async () => {
  await fetchTotalCount()
  await fetchData()
})

/**
 * 添加设备（POST）
 */
 async function addDevice() {
  const deviceId = newDeviceId.value.trim()
  if (!deviceId) return

  try {
    const response = await fetch('http://47.108.221.119:5000/webadddevice', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ machine_id: deviceId })
    })

    if (response.ok) {
      alert("设备添加成功")
      newDeviceId.value = ''
      fetchData() // 刷新设备列表
    } else {
      const errorData = await response.json()
      alert(`添加失败：${errorData.message || "未知错误"}`)
    }
  } catch (err) {
    console.error(err)
    alert("网络请求失败，请检查连接")
  }
}

/**
 * 解绑设备（POST）
 */
 async function unbindDevice(id) {
  await fetch('http://47.108.221.119:5000/webunbinddevice', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ id })
  })
  fetchData() // 刷新设备列表
}

/**
 * 切换设备状态（POST）

async function toggleStatus(id) {
  await fetch('http://localhost:3001/api/device/toggle', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ id })
  })
  fetchData() // 刷新设备列表
} */

</script>

<style scoped>
.device-management { padding: 2rem; }
.add-bar { margin-bottom: 1rem; }
.add-bar input { padding: 0.3rem 0.7rem; border-radius: 4px; border: 1px solid #ccc; }
.add-bar button { margin-left: 0.5rem; padding: 0.3rem 1rem; border-radius: 4px; border: none; background: var(--theme-color, #42b983); color: #fff; cursor: pointer; }
.add-bar button:hover { background: var(--theme-color, #369870); filter: brightness(0.9); }
table { width: 100%; border-collapse: collapse; margin-top: 1rem; }
th, td { border: 1px solid #ddd; padding: 0.5rem; text-align: left; }
th { background: #96999b; }
button { margin-right: 0.5rem; }

.pagination {
  margin-top: 1rem;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 1rem;
}
.pagination button {
  padding: 0.3rem 1rem;
  border-radius: 4px;
  border: none;
  background: #42b983;
  color: white;
  cursor: pointer;
}
.pagination button:disabled {
  background: #ccc;
  cursor: not-allowed;
}
</style>